<?php

namespace App\Models;

use App\Http\Controllers\ScoreRuleController;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

/**
 * 阅读任务用户执行表
 * Class ArticleModel
 * @package app\common\model
 */
class ReadingTaskExecute extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'reading_task_execute';


    /**
     * 获取阅读任务下的作品数据库列表
     * @param task_id string 阅读任务id
     */
    public function userIsExecute($task_id)
    {
        return $this->where('task_id', $task_id)->first();
    }


    /**
     * 判断某个任务的阅读任务是否完成
     * @param user_id 用户id
     * @param task_id 阅读任务id
     */
    public function readingTaskProgress($user_id, $account_id, $task_id)
    {
        $reading_task_execute = $this->where('user_id', $user_id)->where('task_id', $task_id)->first();
        if ($reading_task_execute && ($reading_task_execute['progress'] == 100 || $reading_task_execute['progress'] == '100.00')) {
            return false;
        }
        //更新数据库阅读任务进度
        $readingTaskExecuteWorksModel = new ReadingTaskExecuteWorks();
        $readingTaskDatabaseModel = new ReadingTaskDatabase();
        $reading_task_database_id = $readingTaskDatabaseModel->getReadingTaskDatabaseList($task_id);
        $reading_task_database_id = array_column($reading_task_database_id, 'database_id');
        $competiteActivityWorksDatabaseModel = new CompetiteActivityWorksDatabase();
        $database_reading_number = $readingTaskExecuteWorksModel->readingWorksNumber($user_id, $task_id); //获取所有阅读的作品数量
        $database_works_number = $competiteActivityWorksDatabaseModel->databaseWorksNumber($reading_task_database_id); //获取该任务下的所有数据库数据
        if ($database_reading_number >= $database_works_number) {
            $progress = 100;
        } else {
            $progress = sprintf("%.2f", $database_works_number / $database_reading_number);
        }
        if ($reading_task_execute) {
            $reading_task_execute->progress = $progress;
            $reading_task_execute->account_id = $account_id;
            $reading_task_execute->save();
        } else {
            $this->task_id = $task_id;
            $this->user_id = $user_id;
            $this->account_id = $account_id;
            $this->progress = $progress;
            $this->save();
        }
        return $progress;
    }

    /**
     * 用户阅读任务列表
     * @param task_id int 阅读任务id
     * @param page int 页码
     * @param limit int 分页大小
     * @param is_finish string 是否完成   1 已完成  2 未完成
     * @param keywords string 搜索关键词（用户昵称检索）
     * @param sort string 排序  1 默认排序  2 完成时间排序
     */
    public function readingTaskUserExecuteList($task_id, $keywords, $is_finish, $sort, $limit = 10)
    {
        $reading_task_info = ReadingTask::select('is_appoint')->where('id', $task_id)->where('is_del', 1)->first();
        if (empty($reading_task_info)) {
            return [];
        }
        $userInfoModel = new UserInfo();
        //获取满足条件的用户id
        if ($reading_task_info['is_appoint'] == 1) {
            $user_id = $userInfoModel->from($userInfoModel->getTable() . ' as u')
                ->join('user_wechat_info as w', 'w.id', '=', 'u.wechat_id')
                ->join('reading_task_appoint_user as a', 'a.user_id', '=', 'u.id')
                ->where(function ($query) use ($keywords) {
                    if ($keywords) {
                        $query->where('w.nickname', 'like', '%' . $keywords . '%');
                    }
                })
                ->where('a.task_id', $task_id)
                ->pluck('u.id')
                ->toArray();
        } else {
            $user_id = $userInfoModel->from($userInfoModel->getTable() . ' as u')
                ->join('user_wechat_info as w', 'w.id', '=', 'u.wechat_id')
                ->where(function ($query) use ($keywords) {
                    if ($keywords) {
                        $query->where('w.nickname', 'like', '%' . $keywords . '%');
                    }
                })
                ->pluck('u.id')
                ->toArray();
        }
        if ($is_finish == 1 || $sort == 2) {
            $res = $userInfoModel->from($userInfoModel->getTable() . ' as u')
                ->select('u.id as user_id', 'w.nickname', 'w.head_img', 'e.progress', 'e.account_id', 'e.change_time')
                ->join('user_wechat_info as w', 'w.id', '=', 'u.wechat_id')
              //  ->join('reading_task_appoint_user as a', 'a.user_id', '=', 'u.id')
                ->join('reading_task_execute as e', 'e.user_id', '=', 'u.id')
                ->where(function ($query) use ($sort) {
                    $query->where('e.progress', '100');
                })
                ->whereIn('u.id', $user_id)
              //  ->where('a.task_id', $task_id)
                ->where('e.task_id', $task_id);
        } else {
            $res = $userInfoModel->from($userInfoModel->getTable() . ' as u')
                ->select('u.id as user_id', 'w.nickname', 'w.head_img', 'e.progress', 'e.account_id', 'e.change_time')
                ->join('user_wechat_info as w', 'w.id', '=', 'u.wechat_id')
            //    ->join('reading_task_appoint_user as a', 'a.user_id', '=', 'u.id')
                ->leftjoin('reading_task_execute as e', 'e.user_id', '=', 'u.id')
                ->where(function ($query) use ($is_finish) {
                    if ($is_finish == 2) {
                        $query->where('e.progress', '<>', '100');
                    }
                })
                ->whereIn('u.id', $user_id)
               // ->where('a.task_id', $task_id)
                ->where('e.task_id', $task_id);
        }

        if ($sort == 1) {
            $res = $res->orderByDesc('e.create_time')->orderBy('u.id');
        } else {
            $res = $res->orderBy('e.change_time')->orderBy('u.id');
        }
        $res = $res->paginate($limit)
            ->toArray();

           
        foreach ($res['data'] as $key => $val) {
            if ($val['progress'] == '100.00') {
                $res['data'][$key]['progress_status'] = 1; //已完成
            } else {
                $res['data'][$key]['progress_status'] = 2; //未完成
            }
            if ($val['account_id']) {
                $res['data'][$key]['account'] = UserLibraryInfo::where('id', $val['account_id'])->value('account');
            } else {
                $res['data'][$key]['account'] = null;
            }
        }

        //查询完成数量
        $res['completed_number'] = $this->userReadingTaskProgress($task_id);
        if ($reading_task_info['is_appoint'] == 1) {
            $appoint_user = ReadingTaskAppointUser::where('task_id', $task_id)->count();
            $res['unfinished_number'] = $res['completed_number'] - $appoint_user <= 0 ? 0 : $res['completed_number'] - $appoint_user;
        } else {
            $res['unfinished_number'] = null;
        }

        return $res;
    }

    /**
     * 获取用户 已读完数量、阅读中数量
     * @param user_id 用户id
     * @param task_id 任务id
     */
    public function userReadingTaskNumebr($task_id = null, $user_id = null)
    {
        $finished_number = $this->userReadingTaskProgress($task_id, $user_id); //已完成
        $unfinished_number = $this->userReadingTaskProgress($task_id, $user_id, 2); //未完成

        return ['finished_number' => $finished_number, 'unfinished_number' => $unfinished_number];
    }


    /**
     * 获取用户 未阅读数量
     * @param user_id 用户id
     * @param execute_number 当前用户正在执行中的数量
     */
    public function userReadingTaskUnreadNumber($user_id, $execute_number)
    {
        //获取所有的任务数量
        $readingTaskAppointUserModel = new ReadingTaskAppointUser();
        $total_number = $readingTaskAppointUserModel->getUserReadingTaskNumebr($user_id);
        $unread_number = $total_number - $execute_number;
        $unread_number = $unread_number >= 0 ? $unread_number : 0; //未阅读数量
        return $unread_number;
    }
    /**
     * 获取任务 未阅读用户数量
     * @param task_id 任务id
     */
    public function readingTaskUnreadUserNumber($task_id)
    {
        //获取所有的任务数量
        $readingTaskModel = new ReadingTask();
        $is_appoint = $readingTaskModel->where('id', $task_id)->value('is_appoint');
        if ($is_appoint == 2) {
            return null; //当前任务不指定用户，则不统计
        }
        $appoint_user_number = ReadingTaskAppointUser::where('task_id', $task_id)->count(); //获取指定用户数量
        $execute_user_number = $this->userReadingTaskProgress($task_id);
        $number = $appoint_user_number - $execute_user_number;
        $number = $number >= 0 ? $number : 0; //未阅读数量
        return $number;
    }

    /**
     * 获取用户阅读完成情况
     * @param user_id 用户id
     * @param task_id 任务id
     * @param is_complete 是否完成 1 完成  2  未完成
     */
    public function userReadingTaskProgress($task_id = null, $user_id = null,  $is_complete = 1)
    {
        $res = $this->where(function ($query) use ($user_id, $task_id, $is_complete) {
            if ($user_id) {
                $query->where('user_id', $user_id);
            }
            if ($task_id) {
                $query->where('task_id', $task_id);
            }
            if ($is_complete == 1) {
                $query->where('progress', '100');
            } else if ($is_complete == 2) {
                $query->where('progress', '<>', '100');
            }
        })->count();
        return $res;
    }
}
